// GoogleAuth.vue
<template>
  <div class="google-auth">
    <div v-if="!isAuthenticated" class="login-section">
      <h2>登录</h2>
      <button @click="loginWithGoogle" :disabled="loading" class="google-login-btn">
        <span v-if="loading">登录中...</span>
        <span v-else>使用Google登录</span>
      </button>
    </div>
    
    <div v-else class="user-section">
      <h2>欢迎回来！</h2>
      <div class="user-info">
        <img :src="user.picture" :alt="user.name" class="user-avatar">
        <div class="user-details">
          <p><strong>姓名:</strong> {{ user.name }}</p>
          <p><strong>邮箱:</strong> {{ user.email }}</p>
        </div>
      </div>
      <button @click="logout" class="logout-btn">登出</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

// 响应式数据
const isAuthenticated = ref(false)
const user = ref(null)
const loading = ref(false)

// API基础URL
// const API_URL = 'http://localhost:9000'
const API_URL = 'https://api.tiffanylamps.com.cn'

// 设置axios默认配置
axios.defaults.baseURL = API_URL

// 检查本地存储的token
onMounted(() => {
  const token = localStorage.getItem('authToken')
  if (token) {
    // 设置axios默认header
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
    // 验证token有效性
    validateToken()
  }
  
  // 检查是否是从Google OAuth重定向回来的
  handleOAuthCallback()
})

// 使用Google登录
const loginWithGoogle = async () => {
  try {
    loading.value = true
    
    // 获取Google授权URL
    const response = await axios.get('/auth/google')
    const { authUrl } = response.data
    
    // 重定向到Google授权页面
    window.location.href = authUrl
    
  } catch (error) {
    console.error('获取Google授权URL失败:', error)
    alert('登录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理OAuth回调
const handleOAuthCallback = async () => {
  const urlParams = new URLSearchParams(window.location.search)
  const code = urlParams.get('code')
  console.log("🚀 ~ handleOAuthCallback ~ code:", code)
  const error = urlParams.get('error')
  
  if (error) {
    console.error('OAuth error:', error)
    alert('登录失败: ' + error)
    // 清理URL参数
    window.history.replaceState({}, document.title, window.location.pathname)
    return
  }
  
  if (code) {
    try {
      loading.value = true
      
      // 发送授权码到后端
      const response = await axios.post('/auth/google/callback', { code })
      
      if (response.data.success) {
        const { token, user: userData } = response.data
        
        // 保存token到本地存储
        localStorage.setItem('authToken', token)
        
        // 设置axios默认header
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        
        // 更新状态
        isAuthenticated.value = true
        user.value = userData
        
        console.log('登录成功:', userData)
      }
      
    } catch (error) {
      console.error('OAuth回调处理失败:', error)
      alert('登录失败，请重试')
    } finally {
      loading.value = false
      // 清理URL参数
      window.history.replaceState({}, document.title, window.location.pathname)
    }
  }
}

// 验证token有效性
const validateToken = async () => {
  try {
    const response = await axios.get('/user/profile')
    if (response.data.user) {
      isAuthenticated.value = true
      user.value = response.data.user
    }
  } catch (error) {
    console.error('Token验证失败:', error)
    // Token无效，清理本地存储
    localStorage.removeItem('authToken')
    delete axios.defaults.headers.common['Authorization']
  }
}

// 登出
const logout = async () => {
  try {
    await axios.post('/auth/logout')
  } catch (error) {
    console.error('登出请求失败:', error)
  } finally {
    // 清理本地状态
    localStorage.removeItem('authToken')
    delete axios.defaults.headers.common['Authorization']
    isAuthenticated.value = false
    user.value = null
  }
}
</script>

<style scoped>
.google-auth {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.google-login-btn {
  width: 100%;
  padding: 12px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.google-login-btn:hover {
  background-color: #357ae8;
}

.google-login-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.user-section {
  text-align: center;
}

.user-info {
  display: flex;
  align-items: center;
  margin: 20px 0;
  text-align: left;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
}

.user-details p {
  margin: 5px 0;
}

.logout-btn {
  padding: 10px 20px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: #c82333;
}
</style>